const express = require("express")
const {rules,valid} = require("../../utils/rules")
const svgCaptcha = require('svg-captcha');
const dayjs = require("dayjs")
const jwt = require("jsonwebtoken")
const {sqlRows, sqlArrList} = require("../../sql/rows");
const nanoid = require("nanoid").nanoid
const {listToTree} = require("../../utils");
const login = express.Router()

// 登录接口
login.post("/login",rules([
    {
        name: "username",
        message: "用户名"
    },
    {
        name: "password",
        message: "密码"
    },
    {
        name: "code",
        message: "验证码"
    }
]), valid, async (req, res) => {
    try {
        const {code, username, password, uuid} = req.body
        const [rows] = await req.db.query(`SELECT * FROM ums_user WHERE username LIKE '${username}'`)
        const date = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
        if (rows){
            if (rows.status === 0) {
                return res.status(200).send({
                    message: "当前用户禁用",
                    code: 500,
                    data: null
                })
            }

            if (rows.password !== password) {
                return res.status(200).send({
                    message: "密码错误",
                    code: 500,
                    data: null
                })
            }
            // toLowerCase
            console.log(uuid)
            const captcha = await req.redis.getItem(uuid)
            if (!captcha || code.toLowerCase() !== captcha.toString().toLowerCase()) {
                return res.status(200).send({
                    message: "验证码错误",
                    code: 500,
                    data: null
                })
            }
            // 更新最后登录时间
            await req.db.query(`UPDATE ums_user SET login_time = '${date}' WHERE id = '${rows.id}'`)
            // token
            const token = jwt.sign({
                username,
                companyId: rows.id
            }, 'ec', {
                expiresIn: 43200
            })

            return res.status(200).send({
                code: 200,
                message: "",
                data: {
                    user: rows,
                    token
                }
            })
        }
        return res.status(200).send({
            message: "用户名错误",
            code: 500,
            data: null
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "服务器错误",
            data: e
        })
    }

})
// 获取验证码
login.get("/code", async (req, res) => {
    const captcha = svgCaptcha.create({
        height: 32,
        width: 140,
        size: 4, //验证码长度
        noise: 1, //干扰线条数目
        fontSize: 40,
        color: true,
        ignoreChars: "0oOl1I"
    });
    const uuid = nanoid()
    req.redis.setItem(uuid, captcha.text, 120)
    console.log(captcha.text)
    res.type('svg');
    res.status(200).send({
        data: {
            text: captcha.data,
            uuid
        },
        code: 200,
        message: "",
    });
})
// 修改密码
login.post('/pass', rules([
    {
        name: "oldPassword",
        message: "旧密码"
    },
    {
        name: "newPassword",
        message: "新密码"
    },
]), valid, async (req, res) => {
    try {
        const {rows, jwt, body: {
            newPassword,
            oldPassword
        }} = req
        // console.log(rows)
        if (rows.password === oldPassword) {
            const pass = await req.db.query(`UPDATE ums_user SET password = ${newPassword} WHERE id = '${rows.id}'`)
            if (pass) {
                return res.status(200).send({
                    code: 200,
                    message: "密码修改成功",
                    data: ""
                })
            }
        }
        return res.status(200).send({
            code: 400,
            message: "原始密码错误",
            data: ""
        })
    }catch (e) {
        // console.log(e)
        return res.status(500).send({
            code: 500,
            message: "服务器错误",
            data: e
        })
    }
})

// 根据登录角色获取菜单
login.get("/menulist", async (req, res) => {
    try {
        // 获取角色用户关联信息
        const [roleUser] = await req.db.query(sqlRows('ums_role_or_user', {
            SELECT: 'roleId',
            data: {
                userId: req.rows.id
            }
        }))
        // 获取角色菜单关联信息
        const roleMenu = await req.db.query(sqlRows('ums_role_or_menu',{
            SELECT: 'menuId',
            data: roleUser
        }))
        // 获取菜单表
        const menu = await req.db.query(sqlArrList('ums_menu', {
            list: roleMenu,
            key: 'menuId',
            tableKey: 'menu_id'
        }))
        // 获取角色用户关联表
        const role = await req.db.query(sqlRows('ums_role', {
            data: roleUser
        }))
        if (role.length) {
            // 判断当前角色是否启用
            if (role[0].status === 1) {
                return res.status(200).send({
                    code: 200,
                    data: listToTree(menu),
                    message: ""
                })
            }
            return res.status(200).send({
                code: 400,
                data: '',
                message: "当前角色被禁用"
            })
        }
        return res.status(200).send({
            code: 400,
            data: '',
            message: "当前用户没有授权无法登录"
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "服务器错误",
            data: e
        })
    }
})

module.exports = login